package com.example.springbootlinmtest.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author Linm
 * @Date 2023/11/2 22:22
 */
@Slf4j
@Component
public class MyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        CachedBodyHttpServletRequest cachedBodyHttpServletRequest = new CachedBodyHttpServletRequest(httpServletRequest);
        if (cachedBodyHttpServletRequest.getContentType() != null && cachedBodyHttpServletRequest.getContentType().startsWith("multipart/form-data")) {
            MultipartResolver resolver = new CommonsMultipartResolver(cachedBodyHttpServletRequest.getSession().getServletContext());
            MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(cachedBodyHttpServletRequest);

            // 获取所有的参数名
            Enumeration<String> parameterNames = multipartRequest.getParameterNames();

            // 遍历参数名来获取参数值
            while (parameterNames.hasMoreElements()) {
                String paramName = parameterNames.nextElement();
                String paramValue = multipartRequest.getParameter(paramName);
                log.info("paramName={},paramValue={}",paramName,paramValue);
                // 在这里你可以处理参数...
            }
            // 获取所有的文件参数
            MultiValueMap<String, MultipartFile> fileMap = multipartRequest.getMultiFileMap();

            // 遍历文件参数
            for (Map.Entry<String, List<MultipartFile>> entry : fileMap.entrySet()) {
                String paramName = entry.getKey();
                List<MultipartFile> files = entry.getValue();
                log.info("paramName={},files={}",paramName,files.get(0).getOriginalFilename());
                // 在这里你可以处理文件...
            }



            MultipartHttpServletRequest newMultipartRequest = new StandardMultipartHttpServletRequest(httpServletRequest) {
                @Override
                public Iterator<String> getFileNames() {
                    return multipartRequest.getFileNames();
                }

                @Override
                public MultipartFile getFile(String name) {
                    return multipartRequest.getFile(name);
                }

                @Override
                public List<MultipartFile> getFiles(String name) {
                    return multipartRequest.getFiles(name);
                }

                @Override
                public Map<String, MultipartFile> getFileMap() {
                    return multipartRequest.getFileMap();
                }

                @Override
                public MultiValueMap<String, MultipartFile> getMultiFileMap() {
                    return multipartRequest.getMultiFileMap();
                }
            };

// 在过滤器链中传递新的MultipartHttpServletRequest
            chain.doFilter(newMultipartRequest, response);
        } else {
            // 对于非multipart/form-data请求，使用HttpServletRequestWrapper处理
            HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(httpServletRequest);
            // 在这里你可以处理其他类型的请求...
            chain.doFilter(requestWrapper, response);
        }
    }

    @Configuration
    public static class FilterConfig {
        @Bean
        public FilterRegistrationBean<MyFilter> myFilterRegistration() {
            FilterRegistrationBean<MyFilter> registration = new FilterRegistrationBean<>();
            registration.setFilter(new MyFilter());
            registration.addUrlPatterns("/*");
            registration.setName("myFilter");
            registration.setOrder(1);
            return registration;
        }
    }
}
